package com.wugh.fast.security.core.web;


import com.alibaba.fastjson.JSON;
import com.wugh.fast.kernel.util.HttpUtils;
import com.wugh.fast.module.api.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述: 用户信息验证成功后的处理器
 * <pre>
 *     1.主要返回用户的信息
 *     2.记录登录日志
 *     3.重定向会上一次请求的内容
 * </pre>
 *
 * @author wugh
 * @date 2018-09-05 10:41
 */
@Slf4j
public class JsonAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        String ip = HttpUtils.getIpAddress(request);
        Object principal = authentication.getPrincipal();
        if (HttpUtils.isAjaxRequest(request)) {
            ResponseVO<Object> ok = ResponseVO.ok(principal);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ok));
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
